// Fill out your copyright notice in the Description page of Project Settings.


#include "MyLoadingWidget.h"
#include "Components/Image.h"
#include "Components/ProgressBar.h"

void UMyLoadingWidget::NativeConstruct()
{
	Super::NativeConstruct();

	if (Hamster_Progress_Bar)
	{
		Hamster_Progress_Bar->SetPercent(0.0f);
	}

	GetWorld()->GetTimerManager().SetTimer(
		LoadingTimeHandle,
		this,
		&UMyLoadingWidget::UpdateProgressBar,
		0.05f,
		true,
		0.0f
	);

	if (BackGround)
	{
		UTexture2D* BackGoundTexture = LoadObject<UTexture2D>(nullptr, TEXT("/Game/Image/Image_2"));
		if (BackGoundTexture)
		{
			SetFullScreenImage(BackGoundTexture);
		}
		else
		{
			UE_LOG(LogTemp, Warning, TEXT("In Loading Widget, BackGroundTexture is not Loaded!"));
			if (GEngine)
			{
				GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Black, TEXT("In Loading Widget, BackGoundTexture is not Loaded!"));
			}
		}

	}
}

void UMyLoadingWidget::UpdateProgressBar()
{
	CurrentProgress += 0.016;

	SetProgressBarValue(CurrentProgress);

	if (CurrentProgress >= 1.0f)
	{
		GetWorld()->GetTimerManager().ClearTimer(LoadingTimeHandle);
	}
}

void UMyLoadingWidget::SetProgressBarValue(float Value)
{
	float value = FMath::Clamp(Value, 0.0f, 1.0f);

	if (value >= 1.0f)
	{

		GameLoadingComplete.Broadcast();

		// Value is bigger than 1.0f
		// Remove and BroadCast To GameMode
		RemoveFromParent();

		UE_LOG(LogTemp, Warning, TEXT("Progress Bar Value is Bigger Than 1.0f!"));
		if (GEngine)
		{
			GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Black, TEXT("Progress Bar Value is Bigger Than 1.0f!"));
		}
	}

	if (Hamster_Progress_Bar)
	{
		Hamster_Progress_Bar->SetPercent(value);
	}
}

void UMyLoadingWidget::SetFullScreenImage(UTexture2D* backgroundTexture)
{
	if (!BackGround) return;

	// Set Pivot
	BackGround->SetRenderTransformPivot(FVector2D(0.5f, 0.5f));

	// Set Translation
	BackGround->SetRenderTranslation(FVector2D(0, 0));

	// Set viewport size
	FVector2D ViewportSize;
	if (GEngine)
	{
		GEngine->GameViewport->GetViewportSize(ViewportSize);
	}

	BackGround->SetBrushFromTexture(backgroundTexture);
	BackGround->SetBrushSize(ViewportSize);

	UE_LOG(LogTemp, Warning, TEXT("In Login Widget, BackGound is Set To ViewPort Size"));
	if (GEngine)
	{
		GEngine->AddOnScreenDebugMessage(-1, 1.0f, FColor::Black, TEXT("In Login Widget, BackGound is Set To ViewPort Size"));
	}

}


